package linked;

public class DoubleLinkedListADT<T> {
    public Node<T> head;
    public DoubleLinkedListADT() {
        //创建头指针
        head=new Node<>();
    }
    public boolean removeFirst(){
        if (head.next==null) {
            System.out.println("链表为空，不能删除");
            return false;
        }
        head.next=head.next.next;
        head.next.prev=head;

        return true;
    }
    public DoubleLinkedListADT<T> addFirst(Node<T> node){
       if (head.next==null) head.next=node;
       node.next=head.next;
       head.next.prev=node;
       head.next=node;
       node.prev=head;
        return this;
    }

    public DoubleLinkedListADT<T> addLast(Node<T> node){
        Node<T> temp=head;
        //哨兵指向队尾
        while (temp.next!=null){
            temp=temp.next;
        }
        temp.next=node;
        node.prev=temp;
        return this;
    }
    /**
     * 正序遍历输出
     */

    public void showList(){
        if (head.next==null) {
            System.out.println("链表为空");
            return;
        }
        Node<T> temp=head;
        while (temp.next!=null){

            temp=temp.next;
            System.out.println(temp.data);
        }
    }

    public void showListReversed(){
        if (head.next==null) {
            System.out.println("链表为空");
            return;
        }
        Node<T> temp=getTail();
        while (temp!=head){
            System.out.println(temp.data);
            temp=temp.prev;

        }
    }

    /**
     * 获取链表链表首个元素
     * @return
     */
    public Node<T> getHead(){
        return head.next;
    }

    public Node<T> getTail(){
        Node<T> temp=head;
        while (temp.next!=null){

            temp=temp.next;

        }
        return temp;
    }

    public void swap(Node<T> node1,Node<T> node2){
        Node<T> t1=null;
        Node<T> t2 = null;
        //保存t2的前一个节点
        Node<T> previous;
        //遍历找到t1,t2节点
        if (head.next==null) {
            System.out.println("链表为空");
            return;
        }
        Node<T> temp=head;
        while (temp.next!=null){

            temp=temp.next;
           if (temp==node1) t1=temp;
           if (temp==node2) t2=temp;
        }
        //保存后节点的前节点t,重新组织连接
        previous=t2.prev;
        previous.next=t2.next;
        t2.next.prev=previous;

        t2.next=t1.next;
        t1.next.prev=t2;
        t1.prev.next=t2;
        t2.prev=t1.prev;


        t1.next=previous.next;
        previous.next.prev=t1;
        previous.next=t1;
        t1.prev=previous;



    }
}
